<template>
    <div class="report-data-list">
        <!-- Search form -->
        <el-form :inline="true"  class="demo-form-inline" size="small">
            <el-form-item label="场馆名称">
                <el-input v-model="venueName" placeholder="请输场馆名称" clearable>
                    <template #prefix
                        ><el-icon class="el-input__icon"><Search /></el-icon
                    ></template>
                </el-input>
            </el-form-item>
            <el-form-item label="用户昵称">
                <el-input v-model="nickName" placeholder="请输入用户昵称" clearable>
                    <template #prefix><el-icon class="el-input__icon"><Search /></el-icon></template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="load">查询</el-button>
                <el-button type="danger" @click="clear">重置</el-button>
                <el-button type="success" @click="exportToExcel">导出Excel</el-button>
            </el-form-item>
        </el-form>

        <!-- Report data table -->
        <el-table :data="reportData" stripe border v-loading="loading" :max-height="getTableHeight()">
            <el-table-column prop="userId" label="用户ID" sortable />
            <el-table-column prop="nickName" label="用户昵称" />
            <el-table-column prop="eventName" label="活动名称" />
            <el-table-column prop="name" label="场馆名称" />
            <el-table-column prop="address" label="地址" />
            <el-table-column prop="reservationDate" label="预约日期" />
            <el-table-column prop="times" label="时间" />
            <el-table-column prop="numPeople" label="参与人数" />
        </el-table>

        <!-- Pagination -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { getTableHeight } from '../utils/role';
import { formatTimes, formatDate } from '../utils/time';
import * as XLSX from 'xlsx';

const reportData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const nickName = ref('');
const venueName = ref('');
const total = ref(0);
const loading = ref(false);

const load = async () => {
    loading.value = true;
    try {
        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            nickName: nickName.value,
            venueName: venueName.value,
        };
        const userString = sessionStorage.getItem('user');
        const user = userString ? JSON.parse(userString) : null;
        if ([3, 4, 5].includes(user.role)) {
            params.role = user.role;
        }
        const response = await axios.get('http://localhost:8080/api/reservations/list', { params });
        if (response.data.status === 200) {
            reportData.value = response.data.data.records.map((r) => ({
                ...r,
                reservationDate: formatDate(r.reservationDate),
                times: formatTimes(r.times),
            }));
            total.value = response.data.data.total;
            currentPage.value = response.data.data.current;
            pageSize.value = response.data.data.size;
        } else {
            ElMessage.error('获取报告数据失败');
        }
    } catch (error) {
        ElMessage.error('请求报告数据出错: ' + error.message);
    } finally {
        loading.value = false;
    }
};

const clear = () => {
    venueName.value = ''
    nickName.value = ''
    currentPage.value = 1;
    load();
};

const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    load();
};

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    load();
};

const exportToExcel = () => {
    const data = reportData.value.map((item) => ({
        用户ID: item.userId,
        用户昵称: item.nickName,
        场馆名称: item.name,
        活动名称: item.eventName,
        地址: item.address,
        预约日期: item.reservationDate,
        时间: item.times,
        参与人数: item.numPeople,
    }));

    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '报告数据');

    // 生成二进制字符串
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

    // 创建Blob对象
    const blob = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });

    // 创建下载链接并触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '报告数据.xlsx';
    link.click();

    ElMessage.success('Excel文件导出成功');
};

onMounted(() => {
    load();
});
</script>

<style scoped>
.report-data-list {
    padding: 20px;
}

.el-pagination {
    margin-top: 20px;
    justify-content: center;
}
</style>
